//
//  LKLWebViewController.m
//  LKLWebResDemo
//
//  Created by haoyingjie on 2021/9/3.
//

#import "LKLWebViewController.h"
#import <WebKit/WebKit.h>
#import "WXApi.h"
#import "Toast.h"
#import <LKLPaymentSdk/UPPaymentControl.h>
#import <LKLPaymentSdk/LKLUnionCashier.h>
#import "InputLKLResultModel.h"
#import "YunOrderListModel.h"
#import "UIApplication+Extension.h"
@interface LKLWebViewController ()<WKNavigationDelegate,WKScriptMessageHandler,WKUIDelegate>
@property (nonatomic, strong)WKWebView *webView;

@end

@implementation LKLWebViewController
- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    NSLog(@"LKLWebViewController ---dealloc");
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self addWebView];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
}
- (void)didBecomeActive {
    if (![UIApplication.topViewController isKindOfClass:[LKLWebViewController class]]) {
        return;
    }
    WK(weakSelf)
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_GetYunOrderInfo];
    // getYunPayOrderStatus 新接口 但是人跑了
    [TTHttpRequest postWithUrl:url parameters:self.respData.out_order_no success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSLog(@"%@", responseObject);
        if ([responseObject[@"code"]integerValue] == 10000) {
            YunOrderListModel * result = [YunOrderListModel modelWithDictionary:responseObject[@"data"]];
            if (result.isSucceed) {
                [SVProgressHUD showWithStatus:@"支付成功~"];
                [SVProgressHUD dismissWithDelay:1];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}
- (void)addWebView{
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
    WKUserContentController *userCC = config.userContentController;
    [userCC addScriptMessageHandler:self name:@"LKLWebObject"];
    [userCC addScriptMessageHandler:self name:@"LKLUnionCashier"];

    config.userContentController = userCC;

    self.webView = [[WKWebView alloc]initWithFrame:[UIScreen mainScreen].bounds configuration:config];
    self.webView.backgroundColor = [UIColor whiteColor];
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    [self.view addSubview:self.webView];
    
    [LKLUnionCashier shareInstanceWithWebView:self.webView];
    
    NSString *httpsStr = self.respData.counter_url;
    NSURL *url = [NSURL  URLWithString:httpsStr];;
    NSURLRequest *httpsRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
    [_webView loadRequest:httpsRequest];

    if(@available(iOS 11.0, *)) {
        _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
}

#pragma mark ==
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
    NSLog(@"webViewDidStartLoad %@", webView.URL.absoluteString);
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"webView error is %@",error);

}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"webView finish is");

}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"webView error is %@",error);
    

}
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *_Nullable))completionHandler {
    NSLog(@"didReceiveAuthenticationChallenge: %@", webView.URL.absoluteString);
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        if (challenge.previousFailureCount == 0) {
            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
        } else {
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        }
    }
}

#pragma mark - WKScriptMessageHandler
/// 通过接收JS传出消息的name进行捕捉的回调方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"userContentController: %@", message.name);
    if ([message.name isEqualToString:@"LKLWebObject"]) {
        NSDictionary *bodyInfo = message.body;
        NSString *methodName = bodyInfo[@"method"]?bodyInfo[@"method"]:@"";
        if ([methodName isEqualToString:@"jumpAlipay"]) {//跳转支付宝
            NSString *url = bodyInfo[@"url"];
            [self jumpToAlipayWithUrl:url];
        }else if ([methodName isEqualToString:@"jumpWxApplet"]){
            [self jumpToWechatMiniPrograme:bodyInfo];
        }else if ([methodName isEqualToString:@"closeWindow"]){
             //做相关业务操作
        }
    }else if ([message.name isEqualToString:@"LKLUnionCashier"]) {
        NSDictionary *bodyInfo = message.body;
        NSDictionary *data = bodyInfo[@"data"];
        NSString *methodName = bodyInfo[@"method"]?bodyInfo[@"method"]:@"";
        if ([methodName isEqualToString:@"startPay"]) {
            [[UPPaymentControl defaultControl]startPay:data[@"tn"] fromScheme:@"lklPayDemo" mode:data[@"serverMode"] viewController:self];
        }else if ([methodName isEqualToString:@"startSEPay"]) {
            [[UPPaymentControl defaultControl]startPay:data[@"tn"] fromScheme:@"lklPayDemo" mode:data[@"serverMode"] viewController:self];
        }else if ([methodName isEqualToString:@"mobileBrand"]){
            NSString *deviceType = [[UIDevice currentDevice] model];
            NSLog(@"deviceType----%@",deviceType);
        }
        
    }
}

/*
跳转支付宝
注意：必须在info.plist中增加alipayqr白名单（LSApplicationQueriesSchemes下增加）
 */
-(void)jumpToAlipayWithUrl:(NSString *)url{
    
    if (![[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:url]]) {//未安装
        [self.view makeToast:@"请先下载“支付宝”客户端"];
        return;
    }
    
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:nil];
    } else {
        // Fallback on earlier versions
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
        
    }
}
//跳转微信小程序
/*
 dic中需要包含的数据
 username
 path
 programType
 */
-(void)jumpToWechatMiniPrograme:(NSDictionary *)dic{
    NSString *userName = dic[@"userName"];
    NSString *path = dic[@"path"];
    int programType = [NSString stringWithFormat:@"%@",dic[@"programType"]].intValue;

    [self jumpWxApplet:userName programPath:path programType:programType];
}
//跳转小程序Wechat_Applet
-(void)jumpWxApplet:(NSString *)userName programPath:(NSString *)path  programType:(int)programType {
    if ([WXApi isWXAppInstalled]) {
        //微信注册
        
        if ([WXApi registerApp:S.appKey_weixin universalLink:S.universalLink]) {
            WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
            //拉起的小程序的username
            launchMiniProgramReq.userName = userName;
            launchMiniProgramReq.path = path;
            //拉起小程序的类型
            launchMiniProgramReq.miniProgramType = programType;
            return [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
                NSLog(@"sendReq result %d",success);
            }];
        }else{
             
        }
    }else{
        [self.view makeToast:@"请下载“微信”完成注册"];
    }
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(WK_SWIFT_UI_ACTOR void (^)(WKNavigationActionPolicy))decisionHandler {
    NSLog(@"decidePolicyForNavigationAction --- %@", navigationAction.request.URL.absoluteString);
    // https://www.hqhh520.top/
    if ([navigationAction.request.URL.absoluteString containsString:@"www.hqhh520.top"]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

@end
